import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';


import 'package:path_provider/path_provider.dart';

import 'utils.dart';
///tcp 传递文件工具类
class SocketTcpUtils {
  SocketTcpUtils._internal();

  static SocketTcpUtils? instance;

  static getInstance() {
    instance ??= SocketTcpUtils._internal();
    return instance;
  }

  factory SocketTcpUtils() => getInstance();

  Socket? _socket;
  final int _serverPort = 5556; //本机服务器端口，监听消息

  ///分包处理
  final List<int> _fileList = [];
  String _fileName = "";
  int _dataLen = 0;

  //各个固定的字节长度
  final int _headerSize = 1,_nameSize = 1,_dataSize = 4,_footerSize = 1;

  ///开启tcp 连接服务端
  void startTcpConnectServer(List<int> msg, String ip) async {
    await Socket.connect(
      ip,
      _serverPort,
      timeout: const Duration(seconds: 3),
    ).then((socket) {
      _socket = socket;
      _socket?.add(msg);
      print('device connect success');
      _socket?.close();
      // _socket?.listen(onData,
      //     onError: onError, onDone: onDone, cancelOnError: false);  // 订阅流
    });
  }

  ///TCP 服务端
   void startListenTcpClient(String ip,void onReceiving(),void onDone()) async {
    print('4444 $ip');
    ServerSocket serverSocket = await ServerSocket.bind(
        InternetAddress(ip), _serverPort, shared: true);
    Directory? tempDir = await getExternalStorageDirectory();
    //遍历所有连接到服务器的套接字
    await for (Socket socket in serverSocket) {
      socket.cast<Uint8List>().listen((data) {
        print("from ${socket.remoteAddress.address} data:" +
            data.length.toString());
        print('aaa ' + tempDir!.path);
        print('ddd ' + data[data.length - 1].toString());

        //第一包数据
        if (data[0] == 0x24 && _dataLen == 0) {
          onReceiving();
          _fileList.clear();
          //tcp单包65535 所以第一包里面必定含完整的文件名
          // Uint8List? bytes = Uint8List.fromList(data);
          int nameLen = data[1];
          _fileName = String.fromCharCodes(data.sublist(_headerSize + _nameSize, _headerSize + _nameSize + nameLen));
          _dataLen = data.buffer.asByteData(_headerSize + _nameSize + nameLen,_dataSize).getInt32(0);
          _fileList.addAll(data.sublist(_headerSize + _nameSize + nameLen+_dataSize, data.length));
        }else{
          _fileList.addAll(data);
        }

        //最后一包数据
        if (data[data.length - 1] == 0x26 && _dataLen == _fileList.length - 1) {
          print('最后一包数据');
          _dataLen = 0;
          _fileList.removeLast();
          if (Platform.isAndroid) {
            //android端处理 存到本地用户可见的file文件夹下
            File imgFile = File(tempDir.path + "/" + _fileName);
            imgFile.writeAsBytes(_fileList); //your image bytes
            onDone();

           //如果是图片，则跳转到相册
            if(Utils.isImgFile(_fileName)){
              Utils.saveGalleryAndroid(_fileList,tempDir.path + "/" + _fileName);
            }else{
              //别的格式则调用打开方式
            }

          }else if(Platform.isIOS){
            //IOS端处理
            if(Utils.isImgFile(_fileName)) Utils.saveGalleryIOS(_fileList,tempDir.path + "/" + _fileName);
          }

        }

      });
    }
  }




  // 收到消息回调
  static void onData(event) {
    print("---onData---$event");
  }

  // 收到错误回调
  static void onError(err) {
    print("---onError---");
  }

  // 断开回调
  static void onDone() {
    print("---onDone---");
  }

}